﻿<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
    <title>Add Shapefile</title>

    <link rel="stylesheet" href="http://js.arcgis.com/3.14/dijit/themes/claro/claro.css">
    <link rel="stylesheet" href="css/app.css">
    <!--[if !IE]> -->
    <link rel="stylesheet" href="css/fileupload.css">
    <!-- <![endif]-->
    <link rel="stylesheet" href="http://js.arcgis.com/3.14/esri/css/esri.css">
    
    <script src="http://js.arcgis.com/3.14/"></script>
    <script>
        var map;

        require([
          "esri/config",
          "esri/InfoTemplate",
          "esri/map",
          "esri/request",
          "esri/geometry/scaleUtils",
          "esri/layers/FeatureLayer",
          "esri/renderers/SimpleRenderer",
          "esri/symbols/PictureMarkerSymbol",
          "esri/symbols/SimpleFillSymbol",
          "esri/symbols/SimpleLineSymbol",
          "dojo/dom",
          "dojo/json",
          "dojo/on",
          "dojo/parser",
          "dojo/sniff",
          "dojo/_base/array",
          "esri/Color",
          "dojo/_base/lang",
          "dijit/layout/BorderContainer",
          "dijit/layout/ContentPane",
          "dojo/domReady!"
        ],
          function (
          esriConfig, InfoTemplate, Map, request, scaleUtils, FeatureLayer,
          SimpleRenderer, PictureMarkerSymbol, SimpleFillSymbol, SimpleLineSymbol,
          dom, JSON, on, parser, sniff, arrayUtils, Color, lang
        ) {

              parser.parse();

              var portalUrl = "http://www.arcgis.com";//定义门户路径

              esriConfig.defaults.io.proxyUrl = "/proxy/";

              on(dom.byId("uploadForm"), "change", function (event) {// 上传事件绑定，change事件
                  var fileName = event.target.value.toLowerCase();// 转换为小写
                  //sniff这个模块集()标记基于当前浏览器
                  if (sniff("ie")) { //在IE中提取文件的完整路径，文件名
                      var arr = fileName.split("\\");//"\"分组
                      fileName = arr[arr.length - 1];//获取文件名
                  }
                  if (fileName.indexOf(".zip") !== -1) {//判断是否为.zip文件，如果是，则添加文件
                      generateFeatureCollection(fileName);
                  }
                  else {//如果不是，提示信息
                      dom.byId('upload-status').innerHTML = '<p style="color:red">Add shapefile as .zip file</p>';
                  }
              });

              map = new Map("mapCanvas", {
                  basemap: "gray",
                  center: [-41.647, 36.41],
                  zoom: 3,
                  slider: false
              });
              //添加文件
              function generateFeatureCollection(fileName) {
                  var name = fileName.split(".");//根据“.”分组
                  //如果是路径 c:\fakepath  - 需要移除
                  //看到这个链接以获得更多信息: http://davidwalsh.name/fakepath
                  name = name[0].replace("c:\\fakepath\\", "");

                  dom.byId('upload-status').innerHTML = '<b>Loading… </b>' + name; //加载提示信息

                  //定义输入参数生成有关详细信息,请参阅文档其余部分
                  //http://www.arcgis.com/apidocs/rest/index.html?generate.html
                  var params = {
                      'name': name,
                      'targetSR': map.spatialReference,
                      'maxRecordCount': 1000,//最大综合
                      'enforceInputFileSizeLimit': true,//执行输入文件大小限制
                      'enforceOutputJsonSizeLimit': true//执行Json输出大小限制
                  };

                  //generalize features for display Here we generalize at 1:40,000 which is approx 10 meters
                  //当使用web墨卡托这应该工作得很好
                  var extent = scaleUtils.getExtentForScale(map, 40000);//获取地图范围
                  var resolution = extent.getWidth() / map.width;// 获取分辨率
                  params.generalize = true;//概括
                  params.maxAllowableOffset = resolution;//分辨率
                  params.reducePrecision = true; //精度
                  params.numberOfDigitsAfterDecimal = 0;//小数点后的位数

                  var myContent = {
                      'filetype': 'shapefile',//文件类型为shp文件
                      'publishParameters': JSON.stringify(params),//返回一个JSON对象的序列化。
                      'f': 'json',//格式为json
                      'callback.html': 'textarea'
                  };

                  //使用其余的生成操作来生成一个压缩shapefile功能集合
                  //发送一个请求使用默认当前平台。
                  request({
                      url: portalUrl + '/sharing/rest/content/features/generate',//生产操作功能
                      content: myContent,
                      form: dom.byId('uploadForm'),
                      handleAs: 'json',
                      load: lang.hitch(this, function (response) {//返回一个函数,它只会在给定的范围内执行
                          if (response.error) {
                              errorHandler(response.error);
                              return;
                          }
                          var layerName = response.featureCollection.layers[0].layerDefinition.name;//图层名称 
                          dom.byId('upload-status').innerHTML = '<b>Loaded: </b>' + layerName;//显示
                          addShapefileToMap(response.featureCollection);//加载文件
                      }),
                      error: lang.hitch(this, errorHandler)
                  });
              }
              //错误信息
              function errorHandler(error) {
                  dom.byId('upload-status').innerHTML =
                  "<p style='color:red'>" + error.message + "</p>";
              }
              //添加文件
              function addShapefileToMap(featureCollection) {
                  //add the shapefile to the map and zoom to the feature collection extent
                  //If you want to persist the feature collection when you reload browser you could store the collection in
                  //local storage by serializing the layer using featureLayer.toJson()  see the 'Feature Collection in Local Storage' sample
                  //for an example of how to work with local storage.
                  var fullExtent;// 展开范围
                  var layers = [];//图层数组
                  arrayUtils.forEach(featureCollection.layers, function (layer) {//遍历图层
                      var infoTemplate = new InfoTemplate("Details", "${*}");//设置信息模板，显示所有内容
                      var featureLayer = new FeatureLayer(layer, {
                          infoTemplate: infoTemplate
                      });//定义返回结果为featureLayer
                      //绑定单机时间，显示项目信息
                      featureLayer.on('click', function (event) {
                          map.infoWindow.setFeatures([event.graphic]);
                      });
                      //change default symbol if desired. Comment this out and the layer will draw with the default symbology
                      changeRenderer(featureLayer);//改变图层渲染
                      fullExtent = fullExtent ?
                        fullExtent.union(featureLayer.fullExtent) : featureLayer.fullExtent;
                      layers.push(featureLayer);// featureLayer添加到图层数组
                  });
                  map.addLayers(layers);//添加到地图
                  map.setExtent(fullExtent.expand(1.25), true);//定位到新添加地图范围

                  dom.byId('upload-status').innerHTML = "";
              }

              function changeRenderer(layer) {
                  //改变默认的符号特征多边形和集合点
                  var symbol = null;
                  switch (layer.geometryType) {
                      case 'esriGeometryPoint':
                          symbol = new PictureMarkerSymbol({
                              'angle': 0,
                              'xoffset': 0,
                              'yoffset': 0,
                              'type': 'esriPMS',
                              'url': 'http://static.arcgis.com/images/Symbols/Shapes/BluePin1LargeB.png',
                              'contentType': 'image/png',
                              'width': 20,
                              'height': 20
                          });
                          break;
                      case 'esriGeometryPolygon':
                          symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
                            new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
                              new Color([112, 112, 112]), 1), new Color([136, 136, 136, 0.25]));
                          break;
                  }
                  if (symbol) {
                      layer.setRenderer(new SimpleRenderer(symbol));//设置渲染适配器
                  }
              }
          });
    </script>
  </head>
  
  <body class="claro">
    <div id="mainWindow" data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design:'headline',gutters:false" style="width:100%; height:100%;">
      <div data-dojo-type="dijit/layout/ContentPane" id="rightPane" data-dojo-props="region:'right'">
        <div style='padding-left:4px;'>
          <p>
            Add a zipped shapefile to the map.</p><p>Visit the
            <a target='_blank' href="http://doc.arcgis.com/en/arcgis-online/reference/shapefiles.htm">Shapefiles</a> help topic for information and limitations.</p>
              <form enctype="multipart/form-data" method="post" id="uploadForm">
              <div class="field">
                  <label class="file-upload">
                      <span><strong>Add File</strong></span>
                      <input type="file" name="file" id="inFile" />
                  </label>
              </div>
              </form>
              <span class="file-upload-status" style="opacity:1;" id="upload-status"></span>
              <div id="fileInfo">&nbsp;</div>
        </div>
    </div>
    <div id="mapCanvas" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'center'"></div>
  </div>
</body>

</html>
